{% extends 'base_pages/base.html' %}

{% block title %}
{{_("Host Machines")}}
{% endblock %}

{% block header %}
<h1>{{_("Host Machines")}}</h1>
{% endblock %}

{% block content %}
<style>
    .progress-bar {
        margin-bottom: 6px;
    }
    .info-type-title {
        margin-top: 0px;
        margin-bottom: 0px;
        font-size: 1em;
    }
    .disk-name-tag {
        margin-top: 0px;
        margin-bottom: 0px;
        font-size: 0.8em;
    }
</style>
<div style="display: flex; gap: 10px;">
    <button id="addNew">{{_("Add New")}}</button>
    <button id="exportTable">{{_("Export CSV")}}</button>
    <button id="importTable">{{_("Import CSV")}}</button>
</div>
<table id="hostMachinesTable">
    <thead>
        <tr>
            <th>ID</th>
            <th>{{_("Name")}}</th>
            <th>{{_("Description")}}</th>
            <th>{{_("Address")}}</th>
            <th>{{_("CPU Usage")}}</th>
            <th style="min-width: 120px">{{_("Memory & Disk Usage")}}</th>
            <th>{{_("Actions")}}</th>
        </tr>
    </thead>
    <tbody>
        <!-- Rows will be dynamically inserted here -->
    </tbody>
</table>

<script>
    $(document).ready(function () {
        loadHostMachines();

        $('#addNew').click(function () {
            addNewHostMachine();
        });

        $('#exportTable').click(function () {
            ajaxRequest({
                url: '/host-machine-info/export_table',
                type: 'GET',
                success: function (data) {
                    const blob = new Blob([data], { type: 'text/csv' });
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'host_machines.csv';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                },
                error: function (e) {
                    alert('{{_("Export failed")}}: ' + e.responseJSON.error);
                }
            });
        });

        $('#importTable').click(function () {
            const input = $('<input type="file" accept=".csv">');
            input.on('change', function (e) {
                const file = e.target.files[0];
                if (file) {
                    const formData = new FormData();
                    formData.append('file', file);
                    ajaxRequest({
                        url: '/host-machine-info/import_table',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function () {
                            showToast('{{_("Data imported successfully")}}');
                            loadHostMachines();
                        },
                        error: function (e) {
                            alert('{{_("Import failed")}}: ' + e.responseJSON.error);
                        }
                    });
                }
            });
            input.click();
        });

        function loadHostMachines() {
            ajaxGet('/host-machine-info', function (data) {
                $('#hostMachinesTable tbody').empty();
                data.forEach(function (host) {
                    // const cpuUsage = host.status.cpu_count > 0 ? (host.status.cpu_usage / host.status.cpu_count).toFixed(2) : 0;
                    //# <!-- const memoryUsagePercentage = host.status.memory.total > 0 ? ((host.status.memory.used / host.status.memory.total); -->
                    //const memoryUsageText = `${Math.round(host.status.memory.used / 1024 / 1024)}/${Math.round((host.status.memory.total) / 1024 / 1024)} MB (${memoryUsagePercentage})`
                    
                    const { text: memoryUsageText, percentage: memoryUsagePercentage } = formatSizeOccupationBytes(host.status.memory.used, host.status.memory.total)
                    let diskUsageHtml = '';
                    host.status.disks.forEach(function (disk) {
                        const { text: diskUsageText, percentage: diskUsagePercent } = formatSizeOccupationBytes(disk.used, disk.total)

                        diskUsageHtml += `
                                <p class="disk-name-tag">${disk.mountpoint}</p>
                                <div class="progress-bar">
                                    <div class="progress-bar-fill" style="width: ${diskUsagePercent}%;"></div>
                                    <div class="progress-text">${diskUsageText}</div>
                                </div>
                            `;
                    });

                    $('#hostMachinesTable tbody').append(`
                            <tr id="sky-table-row-${host.id}">
                                <td>${host.id}</td>
                                <td class="editable" data-field="name">${host.name}</td>
                                <td class="editable" data-field="description">${host.description}</td>
                                <td class="editable" data-field="address">${host.address}</td>
                                <td class="cpu-usage-cell" >
                                   
                                </td>
                                <td >
                                    <p class="info-type-title">{{_("Memory Usage:")}}</p>
                                    <div class="progress-bar">
                                        <div class="progress-bar-fill" style="width: ${memoryUsagePercentage}%;"></div>
                                        <div class="progress-text">${memoryUsageText}</div>
                                    </div>
                                    <p class="info-type-title">{{_("Disks Usage:")}}</p>
                                    ${diskUsageHtml}
                                </td>
                                <td>
                                    <button class="delete" type="dangerous" data-id="${host.id}">{{_('Delete')}}</button>
                                </td>
                            </tr>
                        `);
                    const cpuUsageCell = document.querySelector(`#sky-table-row-${host.id} .cpu-usage-cell`)
                    console.log(cpuUsageCell)
                    host.status.cpu.cpu_percentages
                    const wrapper = document.createElement('div')
                    cpuUsageCell.appendChild(wrapper)
                    createHeatmap(4,
                        Math.ceil(host.status.cpu.cpu_percentages.length / 4),
                        host.status.cpu.cpu_percentages,
                        wrapper,
                        { min: 0, max: 100 })
                });
                $('.editable').dblclick(function () {
                    editCell(this);
                });
                $('.delete').click(function () {
                    deleteHostMachine($(this).data('id'));
                });
            });
        }

        function editCell(cell) {
            // Check if the cell already contains an input element
            if ($(cell).find('input').length > 0 || $(cell).find('textarea').length > 0) {
                return;
            }

            const originalValue = $(cell).text();
            let input;
            if ($(cell).data('field') === 'name' || $(cell).data('field') === 'address') {
                input = $('<input type="text" value="' + originalValue + '">');
            } else {
                input = $('<textarea rows="5">' + originalValue + '</textarea>');
            }
            $(cell).html(input);
            input.focus();
            input.blur(function () {
                const newValue = input.val();
                if (newValue !== originalValue) {
                    updateHostMachine($(cell).closest('tr').find('td:first').text(), $(cell).data('field'), newValue);
                }
                $(cell).text(newValue);
            });
        }

        function updateHostMachine(id, field, value) {
            const data = {};
            data[field] = value;
            ajaxRequest({
                url: `/host-machine-info/${id}`,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function () {
                    showToast('{{_("Data saved")}}');
                },
                error: function (e) {
                    alert(`{{_("Update failed")}} ${e.error}`);
                }
            });
        }

        function deleteHostMachine(id) {
            if (confirm('{{_("Are you sure you want to delete this item?")}}')) { // Added confirmation dialog
                ajaxRequest({
                    url: `/host-machine-info/${id}`,
                    type: 'DELETE',
                    success: function () {
                        showToast('{{_("Item deleted")}}');
                        loadHostMachines();
                    },
                    error: function (e) {
                        alert('{{_("Delete failed")}}');
                    }
                });
            }
        }

        function addNewHostMachine() {
            const data = {
                name: `[Untitled Host#${new Date().getUTCMilliseconds()}]`,
                description: '...',
                address: '...'
            };
            ajaxRequest({
                url: '/host-machine-info/create',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function (response) {
                    const newRow = `
                            <tr>
                                <td>${response.id}</td>
                                <td class="editable" data-field="name">${data.name}</td>
                                <td class="editable" data-field="description">${data.description}</td>
                                <td class="editable" data-field="address">${data.address}</td>
                                <td>
                                    <div class="progress-bar">
                                        <div class="progress-bar-fill" style="width: 0%;"></div>
                                        <div class="progress-text">0%</div>
                                    </div>
                                </td>
                                <td>
                                    <div class="progress-bar">
                                        <div class="progress-bar-fill" style="width: 0%;"></div>
                                        <div class="progress-text">0%</div>
                                    </div>
                                </td>
                                <td>
                                    <div class="progress-bar">
                                        <div class="progress-bar-fill" style="width: 0%;"></div>
                                        <div class="progress-text">0%</div>
                                    </div>
                                </td>
                                <td>
                                    <button class="delete" data-id="${response.id}">{{_("Delete")}}</button>
                                </td>
                            </tr>
                        `;
                    $('#hostMachinesTable tbody').append(newRow);
                    $('.editable').dblclick(function () {
                        editCell(this);
                    });
                    $('.delete').click(function () {
                        deleteHostMachine($(this).data('id'));
                    });
                    alert('{{_("Added successfully")}}');
                },
                error: function (e) {
                    alert(`{{_("Add failed")}}: ${e.responseJSON.error}`);
                }
            });
        }

        function showToast(message) {
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.textContent = message;
            document.body.appendChild(toast);
            setTimeout(() => {
                toast.remove();
            }, 3000); // 3 seconds
        }
    });
</script>
{% endblock %}